﻿layui.config({
    base: '/lib/layui/extend/'
}).extend({
    excel: 'excel',
    formSelects: 'formSelects-v4'
}).use(['layer', 'tree', 'table', 'laypage', 'laydate', 'jquery', 'formSelects', 'form', 'upload', 'excel', 'laytpl', 'element', 'code'], function () {
    var form = layui.form, $ = layui.jquery,
        tree = layui.tree,
        table = layui.table,
        laydate = layui.laydate,
        player = parent.layer || layui.layer,
        formSelects = layui.formSelects; //很重要;
    var upload = layui.upload;
    var layer = layui.layer;
    var excel = layui.excel;
    var laytpl = layui.laytpl;
    var element = layui.element;

    var authorityUserListLogic = {
        //初始化
        init: function () {
            self = this;

            this.Parameters = {
                ac: new AsyncCaller(),//异步方法管理
                departmentId: "",
                field: 'sort',
                order: 'asc',
                departmentTreeUrl: "/api/Authority/Department/LoadAllTreeList",
                postTreeUrl: "/api/Authority/Post/LoadAllSelectList",

                forbiddenUrl: "/api/Authority/UserInfo/ForbidOrEnable",
                listUrl: "/api/Authority/UserInfo/LoadList",
                removeUrl: "/api/Authority/UserInfo/Remove",

                addUrl: "/Authority/User/Add",
                modifyUrl: "/Authority/User/Modify",
                changePswUrl: "/Authority/User/ChangePwd",


                bulkimportUrl: "/api/Authority/UserInfo/BulkImportRole",
                tranBulkimportUrl: "/api/Authority/UserInfo/TranBulkImportRole",
                listAll: "/api/Authority/UserInfo/ListAll",

                verifyThatTheFile: "/api/Authority/UserInfo/VerifyThatTheFile",
            };

            this.Parameters.ac
                .pushQueue(function () {
                    //获取部门树状列表信息
                    self.logicFunc.loadDepartmentTreeListInfo(function () {
                        self.Parameters.ac.notifyQueueAsyncFuncComplate();
                    })
                })
                .pushQueue(function () {
                    self.initPage();
                    self.Parameters.ac.notifyQueueAsyncFuncComplate();
                })
                .pushQueue(this.bindEvent)
                .exec();
            //upload上传实例
            var uploadInst = upload.render({
                elem: '#funBtnUpload' //绑定元素
                , url: '/upload/' //上传接口（PS:这里不用传递整个 excel）
                , auto: false //选择文件后不自动上传
                , accept: 'file'
                , choose: function (obj) {// 选择文件回调
                    var files = obj.pushFile()
                    var fileArr = Object.values(files)// 注意这里的数据需要是数组，所以需要转换一下

                    // 用完就清理掉，避免多次选中相同文件时出现问题
                    for (var index in files) {
                        if (files.hasOwnProperty(index)) {
                            delete files[index]
                        }
                    }
                    $('#funBtnUpload').next().val('');
                    self.tools.uploadExcel(fileArr);
                    // uploadExcel(fileArr) // 如果只需要最新选择的文件，可以这样写： uploadExcel([files.pop()])
                }
            });
            //this.initPage();
            //this.bindEvent();
        },
        //初始化列表
        initPage: function () {

            //获取岗位列表
            self.logicFunc.loadPostTreeListInfo();

            //限制左侧树高度
            self.logicFunc.departmentHeight();

            //获取用户信息
            var title =
                [{ type: 'checkbox', fixed: 'left' },
                { field: 'id', title: 'id', hide: true },
                { field: 'name', title: '登录名', width: 130, align: "center", sort: true, fixed: 'left' },
                { field: 'displayname', title: '系统显示名', width: 130, align: "center", sort: true, fixed: 'left' },
                { field: 'mobile_phone', title: '手机号码', width: 130, align: "center", sort: true, fixed: 'left' },
                { field: 'gender', title: '性别', width: 70, align: "center" },
                { field: 'email', title: '邮箱', width: 180, align: "center" },
                { field: 'is_valid', title: '是否启用', width: 140, templet: '#switchValidTpl', align: "center" },
                { field: 'role_names', title: '角色', width: 150, align: "center" },
                { field: 'department_names', title: '部门', width: 150, align: "center" },
                { field: 'post_names', title: '岗位', width: 150, align: "center" },
                { field: 'opt', title: '操作', toolbar: '#gridTool', width: '220', align: 'left', fixed: 'right' }
                ];

            //table加载
            GrdAdmin.tableInit({
                dom: '#userList',
                url: self.Parameters.listUrl,
                field: self.Parameters.field,
                order: self.Parameters.order,
                parameters: {
                    sKeyWords: $("#txtKeyWord").val(),
                    postIds: "",
                    departmentId: ""
                },
                title: title
            });

            //排序监听
            GrdAdmin.tableSort({
                domId: "userList",
                backAction: function (obj) {
                    self.Parameters.field = obj.field;
                    self.Parameters.order = obj.type;
                    self.logicFunc.loadListInfo();
                }
            });

            form.render();
        },
        //绑定事件
        bindEvent: function () {

            ///根据网页变化高度或宽度，调整树高度
            window.onresize = function () {
                self.logicFunc.departmentHeight();
            }

            //查询
            $("#funBtnSearch").on("click", function () {
                self.logicFunc.loadListInfo();
            });

            //新增
            $("#funBtnAdd").on("click", function () {
                self.logicFunc.addInfo();
            });

            //修改
            $("#funBtnEdit").on("click", function () {
                self.logicFunc.modifyInfo();
            });

            //密码
            $("#funBtnPswEdit").on("click", function () {
                self.logicFunc.changePswInfo();
            });

            //删除
            $("#funBtnRemove").on("click", function () {
                if (!$(this).hasClass("layui-btn-disabled")) {
                    self.logicFunc.removeInfo();
                }
            });
            //批量导出
            $("#funBtnderive").on("click", function () {
                self.tools.exportApiDemo();
            });
            //监听(列表操作)
            table.on('tool(userList)', function (obj) {
                var data = obj.data;
                switch (obj.event) {
                    case "funBtnEdit":
                        self.logicFunc.modifyInfo(data);
                        break;
                    case "funBtnPswEdit":
                        self.logicFunc.changePswInfo(data);
                        break;
                    case "funBtnRemove":
                        self.logicFunc.removeInfo(data);
                        break;
                }
            });

            //复选框点击事件
            table.on('checkbox(userList)', function (obj) {
                self.logicFunc.showHideBtn();
            });

            //监听启用/停用操作
            form.on('switch(funBtnValid)', function (obj) {
                self.logicFunc.forbiddenInfo(this.value);
            });

        },
        //逻辑方法
        logicFunc: {

            //部门高度
            departmentHeight: function () {
                var clientHeight = document.documentElement.clientHeight * 0.85;
                $(".layui-card-body").css({ "height": clientHeight });
            },

            ///获取部门树状列表信息
            loadDepartmentTreeListInfo: function (func) {
                GrdAdmin.ajaxRequest({
                    url: self.Parameters.departmentTreeUrl,
                    data: "",
                    success: function (result) {
                        if (result.Code == 1000) {
                            //仅节点左侧图标控制收缩
                            tree.render({
                                elem: '#departmentTreeList',
                                data: result.Data,
                                onlyIconControl: true, //是否仅允许节点左侧图标控制展开收缩 
                                showLine: false,//是否开启连接线
                                accordion: true,
                                target: '_blank', //是否新选项卡打开（比如节点返回href才有效）
                                skin: 'shihuang',
                                click: function (obj) {
                                    self.Parameters.departmentId = obj.data.id;
                                    self.logicFunc.loadListInfo();
                                }
                            });
                        } 
                        if (func) {
                            func();
                        }
                    }
                });
            },

            //获取岗位树状列表
            loadPostTreeListInfo: function () {
                GrdAdmin.ajaxRequest({
                    url: self.Parameters.postTreeUrl,
                    data: "",
                    success: function (result) {
                        if (result.Code == 1000) {
                            //local模式
                            formSelects.data('postList', 'local', {
                                arr: result.Data
                            });
                        }
                    }
                });
            },
            //非事务批量导入
            bulkimport: function (data) {
                GrdAdmin.ajaxRequest({
                    url: self.Parameters.bulkimportUrl,
                    data: data,
                    success: function (result) {
                        if (result.Code == 1000) {
                            GrdAdmin.msg(result.Msg, "成功", function () {
                                self.logicFunc.loadListInfo();
                            });
                        } else {
                            GrdAdmin.msg(result.Msg, "警告");
                        }
                    }
                });
            },
            //事务批量导入
            tranbulkimport: function (data) {
                GrdAdmin.ajaxRequest({
                    url: self.Parameters.tranBulkimportUrl,
                    data: data,
                    success: function (result) {
                        if (result.Code == 1000) {
                            GrdAdmin.msg(result.Msg, "成功", function () {
                                self.logicFunc.loadListInfo();
                            });
                        } else {
                            GrdAdmin.msg(result.Msg, "警告");
                        }
                    }
                });
            },
            //获取数据
            loadListInfo: function () {

                var postIdArry = [];
                var postInfo = formSelects.value('postList');
                if (postInfo.length > 0) {
                    for (var i = 0; i < postInfo.length; i++) {
                        postIdArry.push(postInfo[i].value);
                    }
                }

                GrdAdmin.tableReload({
                    domId: "userList",
                    field: self.Parameters.field,
                    order: self.Parameters.order,
                    parameters: {
                        sKeyWords: $("#txtKeyWord").val(),
                        postIds: postIdArry.join(","),
                        departmentId: self.Parameters.departmentId
                    }
                });
            },

            //增加信息
            addInfo: function () {
                var index = layui.layer.open({
                    title: "增加用户信息",
                    type: 2,
                    resize: false,
                    area: ['700px', '700px'],
                    content: self.Parameters.addUrl,
                    end: function () {
                        $(window).unbind("resize");
                    }
                });
                layui.layer.full(index);
            },

            //修改信息
            modifyInfo: function (data) {

                if (data != undefined && data != null) {

                    GrdAdmin.setUrlParameters(data);

                    var index = layui.layer.open({
                        title: "修改用户信息",
                        type: 2,
                        resize: false,
                        area: ['700px', '700px'],
                        content: self.Parameters.modifyUrl,
                        end: function () {
                            $(window).unbind("resize");
                        }
                    });
                    layui.layer.full(index);
                } else {
                    GrdAdmin.getSingleCheckData({
                        domId: "userList",
                        backAction: function (data) {

                            GrdAdmin.setUrlParameters(data);

                            var index = layui.layer.open({
                                title: "修改用户信息",
                                type: 2,
                                resize: false,
                                area: ['700px', '700px'],
                                content: self.Parameters.modifyUrl,
                                end: function () {
                                    $(window).unbind("resize");
                                }
                            });
                            layui.layer.full(index);
                        }
                    });

                }
            },

            //修改密码
            changePswInfo: function (data) {
                if (data != undefined && data != null) {
                    var index = layui.layer.open({
                        title: "修改用户密码",
                        type: 2,
                        resize: false,
                        area: ['600px', '400px'],
                        content: self.Parameters.changePswUrl + '?data=' + data.gCode,
                        end: function () {
                            $(window).unbind("resize");
                        }
                    });
                    //layui.layer.full(index);
                } else {
                    GrdAdmin.getSingleCheckData({
                        domId: "userList",
                        backAction: function (data) {
                            var index = layui.layer.open({
                                title: "修改用户密码",
                                type: 2,
                                resize: false,
                                area: ['600px', '400px'],
                                content: self.Parameters.changePswUrl + '?data=' + data.gCode,
                                end: function () {
                                    $(window).unbind("resize");
                                }
                            });
                            //layui.layer.full(index);
                        }
                    });

                }
            },

            //启用或停用
            forbiddenInfo: function (id) {
                GrdAdmin.ajaxRequest({
                    url: self.Parameters.forbiddenUrl,
                    data: { id: id },
                    type: GrdAdmin.ajaxGet,
                    success: function (result) {
                        if (result.Code == 1000) {
                            GrdAdmin.msg(result.Msg, "成功", function () {
                                self.logicFunc.loadListInfo();
                            });
                        } else {
                            GrdAdmin.msg(result.Msg, "警告");
                        }
                    }
                });
            },

            //删除信息
            removeInfo: function (data) {
                if (data != undefined && data != null) {
                    GrdAdmin.removeDataByInfo({
                        data: data,
                        removeUrl: self.Parameters.removeUrl,
                        backAction: function (data) {
                            self.logicFunc.loadListInfo();
                        }
                    });
                } else {
                    GrdAdmin.removeDataByDomId({
                        domId: "userList",
                        removeUrl: self.Parameters.removeUrl,
                        backAction: function (data) {
                            self.logicFunc.loadListInfo();
                        }
                    });
                }
            },

            //显示或隐藏删除按钮
            showHideBtn: function () {
                var checkStatus = GrdAdmin.laytable.checkStatus("userList");
                var data = checkStatus.data;
                if (data.length == 0) {
                    //$("#funBtnRemove").show();
                    $("#funBtnRemove").addClass("layui-btn-danger");
                    $("#funBtnRemove").removeClass("layui-btn-disabled");
                } else {
                    var hasSuperUser = false;
                    for (var i = 0; i < data.length; i++) {
                        if (data[i].is_super_user == true) {
                            hasSuperUser = true;
                            break;
                        }
                    }
                    if (hasSuperUser) {
                        //$("#funBtnRemove").hide();
                        $("#funBtnRemove").removeClass("layui-btn-danger");
                        $("#funBtnRemove").addClass("layui-btn-disabled");
                    } else {
                        $("#funBtnRemove").addClass("layui-btn-danger");
                        $("#funBtnRemove").removeClass("layui-btn-disabled");
                        //$("#funBtnRemove").show();
                    }
                }
            },
        },
        //工具
        tools: {
            //导入
            uploadExcel: function (files) {
                try {
                    excel.importExcel(files, {
                        // 可以在读取数据的同时梳理数据
                        /*fields: {
                          'id': 'A'
                          , 'username': 'B'
                          , 'experience': 'C'
                          , 'sex': 'D'
                          , 'score': 'E'
                          , 'city': 'F'
                          , 'classify': 'G'
                          , 'wealth': 'H'
                          , 'sign': 'I'
                        }*/
                    }, function (data, book) {

                        // data: {1: {sheet1: [{id: 1, name: 2}, {...}]}}// 工作表的数据对象
                        // book: {1: {Sheets: {}, Props: {}, ....}} // 工作表的整个原生对象，https://github.com/SheetJS/js-xlsx#workbook-object
                        // 也可以全部读取出来再进行数据梳理
                        data = excel.filterImportData(data, {
                            'name': 'A',
                            'displayname': 'B',
                            'mobile_phone': 'C',
                            'gender': 'D',
                            'email': 'E',
                            'is_valid': 'F',
                            'role': 'G',
                            'depart': 'H',
                            'post': 'I',

                        })
                        var zhanshidata = eval('data[0].' + book[0].SheetNames[0]);
                        var da1 = eval('data[0].' + book[0].SheetNames[0]);
                        da1.splice(0, 1);
                        GrdAdmin.ajaxRequest({
                            url: self.Parameters.verifyThatTheFile,
                            data: da1,
                            success: function (result) {
                                if (result.Code == 1000) {
                                    
                                    var sheetInfo = eval('data[0].' + book[0].SheetNames[0]);
                                    data[0].Sheet1 = result.Data;

                                   var renderdata = excel.filterImportData(data, {
                                        'name': 'name',
                                        'displayname': 'displayname',
                                        'mobile_phone': 'mobile_phone',
                                        'gender': 'gender',
                                        'email': 'email',
                                        'is_valid': 'is_valid',
                                        'role': 'role',
                                        'depart': 'depart',
                                        'post': 'post',

                                    })
                                    layer.open({
                                        title: '文件转换结果'
                                        , area: ['950px', '470px']
                                        , tipsMore: true
                                        , content: laytpl($('#excelExportTpl').html()).render({ data: renderdata, files: files })
                                        , btn: [ '事务导入']
                                        , yes: function (index, layero) {
                                         
                                            self.logicFunc.tranbulkimport(result.Data);

                                        }

                                        , success: function () {

                                            element.render('tab')

                                            //layui.code({})
                                            // 处理合并
                                            for (var file_index in book) {
                                                if (!book.hasOwnProperty(file_index)) {
                                                    continue
                                                }
                                                // 遍历每个Sheet
                                                for (var sheet_name in book[file_index].Sheets) {
                                                    if (!book[file_index].Sheets.hasOwnProperty(sheet_name)) {
                                                        continue
                                                    }
                                                    var sheetObj = book[file_index].Sheets[sheet_name]
                                                    // 仅在有合并参数时进行操作
                                                    if (!sheetObj['!merges']) {
                                                        continue
                                                    }
                                                    // 遍历每个Sheet中每个 !merges
                                                    for (var merge_index = 0; merge_index < sheetObj['!merges'].length; merge_index++) {
                                                        var mergeObj = sheetObj['!merges'][merge_index]
                                                        // 每个合并参数的 s.c 表示左上角单元格的列，s.r 表示左上角单元格的行，e.c 表示右下角单元格的列，e.r 表示右下角单元格的行，计算时注意 + 1
                                                        $('#table-export-' + file_index + '-' + sheet_name + '-' + mergeObj.s.r + '-' + mergeObj.s.c)
                                                            .prop('rowspan', mergeObj.e.r - mergeObj.s.r + 1)
                                                            .prop('colspan', mergeObj.e.c - mergeObj.s.c + 1)
                                                        for (var r = mergeObj.s.r; r <= mergeObj.e.r; r++) {
                                                            for (var c = mergeObj.s.c; c <= mergeObj.e.c; c++) {
                                                                // 排除左上角
                                                                if (r === mergeObj.s.r && c === mergeObj.s.c) {
                                                                    continue
                                                                }
                                                                $('#table-export-' + file_index + '-' + sheet_name + '-' + r + '-' + c).remove()
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    });

                                } else {
                                    GrdAdmin.msg(result.Msg, "警告");
                                }
                            }
                        });

                        // 如果不需要展示直接上传，可以再次 $.ajax() 将JSON数据通过 JSON.stringify() 处理后传递到后端即可
                        /**
                         * 2019-06-21 JeffreyWang 应群友需求，加一个单元格合并还原转换
                         * 思路：
                         * 1. 渲染时为每个cell加上唯一的ID，demo里边采用 table-export-文件索引-sheet名称-行索引-列索引
                         * 2. 根据 book[文件索引].Sheets[sheet名称]['!merge'] 参数，取左上角元素设置 colspan 以及 rowspan，并删除其他元素
                         */

                    })
                } catch (e) {
                    layer.alert(e.message)
                }
            },

            /**
            * 导出接口数据的样例
            * @return {[type]} [description]
            */
            exportApiDemo: function () {
                GrdAdmin.ajaxRequest({
                    url: self.Parameters.listAll,
                    type: GrdAdmin.ajaxGet,
                    success: function (result) {
                        var data = result.Data;
                        // 重点！！！如果后端给的数据顺序和映射关系不对，请执行梳理函数后导出
                        data = excel.filterExportData(data, {
                            name: 'name',
                            displayname: 'displayname',
                            mobile_phone: 'mobile_phone',
                            gender: 'gender',
                            email: 'email',
                            is_valid: 'is_valid',
                            role_names: 'role_names',
                            department_names: 'department_names',
                            post_names: 'post_names',
                        })
                        // 重点2！！！一般都需要加一个表头，表头的键名顺序需要与最终导出的数据一致
                        data.unshift({
                            name: '登录名',
                            displayname: '系统显示名',
                            mobile_phone: '手机号码',
                            gender: '性别',
                            email: '邮箱',
                            is_valid: '是否启用',
                            role_names: '角色',
                            department_names: '部门',
                            post_names: '岗位'
                        })

                        var timestart = Date.now()
                        excel.exportExcel({
                            sheet1: data
                        }, '导出接口数据.xlsx', 'xlsx')
                        //var timeend = Date.now()

                        //var spent = (timeend - timestart) / 1000
                        //layer.alert('单纯导出耗时 ' + spent + ' s')
                    }
                    , error: function () {
                        layer.alert('获取数据失败，请检查是否部署在本地服务器环境下')
                    }
                });


            }
        }
    };
    authorityUserListLogic.init();
});
